# -*- coding: utf-8 -*-
import traceback
import sys
import os
import json

# 美化print输出内容
from prettytable import PrettyTable

def get_line(json_obj) -> list:
    name = json_obj["name"]
    clazz = json_obj["class"]
    method = json_obj["method"]
    line = json_obj["line"]

    class_info = get_info(clazz)
    method_info = get_info(method)
    line_info = get_info(line)

    return [name,class_info,method_info,line_info]



def get_info(json_obj) -> str:
    covered = json_obj["covered"]
    total = json_obj["total"]
    return f"{ round(float(covered) * 100/float(total),2) }%({covered}/{total})"


# 输出 单测覆盖率json 数据到面板
def show_data(json_obj):

    # 先打印表头
    # print(f"name    class   method  line")
    table = PrettyTable(["name","class(%)","method(%)","line(%)"])
    # 对齐方式：l=left c=center r=right
    table.align = "l"
    # 设置标题
    title = json_obj["name"]
    if len(title) >0:
        table.title = title

    # 先打印 覆盖率 列表
    packages = json_obj["packages"]
    for package in packages:

        package_line = get_line(package)
        table.add_row(package_line)
        
        # sourcefile 属于 package，紧跟着打印出来
        sourcefiles = package["sourcefiles"]
        for sourcefile in sourcefiles:
            sourcefile_line = get_line(sourcefile)
            table.add_row(sourcefile_line)
            
    print(table)

    # 输出汇总信息
    all_class_info = get_info(json_obj["class"]) # 类的覆盖率
    all_method_info = get_info(json_obj["method"]) # 方法的覆盖率
    all_line_info = get_info(json_obj["line"]) # 行覆盖率

    tests = json_obj["tests"] # 单元测试内容
    tests_info = get_info({"covered":tests["passed"],"total":tests["total"]})
    tests_cost = tests["time"]

    report_line = f"单测覆盖率：{all_line_info} 行覆盖率\n单测通过率：{tests_info} 方法数\n单测总耗时：{tests_cost}秒"
    print(f"{report_line}")
    


# def main() -> int:
#     script_path = os.path.abspath(__file__) # 脚本所在绝对路径
#     dir_path = os.path.dirname(script_path) # 脚本目录绝对路径
#     json_path = os.path.join(dir_path,"build","result.json")
#     with open(json_path,"r") as json_file:
#         json_obj = json.load(json_file)
#         show_data(json_obj)
#     return 1  

# # main函数入口
# if __name__ == '__main__':
#     sys_ret = 0
#     try:
#         sys_ret = main()
#     except Exception as e:
#         print(e)
#         traceback.print_exc()
#         sys_ret = 1
#     finally:
#         sys.exit(sys_ret)